﻿using System.Collections.Generic;
using UnityEngine;

public class FlockMgr : MonoBehaviour
{
    public FlockItem itemPrefab;
    List<FlockItem> items = new List<FlockItem>();

    [Range(10, 500)]
    public int startingCount = 250;
    const float ItemDensity = 0.08f;

    public FlockBehavior behavior;

    void Start()
    {
        for (int i = 0; i < startingCount; i++)
        {
            FlockItem itemAgent = Instantiate(
                itemPrefab,
                Random.insideUnitCircle * startingCount * ItemDensity,
                Quaternion.Euler(Vector3.forward * Random.Range(0f, 360f)),
                transform
                );
            itemAgent.name = "Item " + i;
            items.Add(itemAgent);
        }
    }

    void Update()
    {
        foreach (FlockItem item in items)
        {
            List<Transform> neighbors = GetNeighborObjects(item);
            Vector2 force = behavior.Force(item, neighbors);
            item.AddFlockForce(force);
        }
    }

    List<Transform> GetNeighborObjects(FlockItem item)
    {
        float radius = item.NeighborRadius;
        List<Transform> neigbhors = new List<Transform>();
        Collider2D[] colliders = Physics2D.OverlapCircleAll(item.transform.position, radius);

        foreach (Collider2D c in colliders)
        {
            if (c != item.Collider)
            {
                neigbhors.Add(c.transform);
            }
        }

        return neigbhors;
    }
}
